<?php

namespace App\Http\Controllers\Activity\Web;

use App\Http\Controllers\BaseController;
use App\Http\Validate\Activity\ActivityValidate;
use App\Jobs\Export\Export;
use App\Models\Activity\ActivityModel;
use App\Service\Activity\ActivityDataService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ActivityDataController extends BaseController
{
    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function joinStatistics(Request $request): JsonResponse
    {
        $params = ActivityValidate::joinStatisticsValidate($request->all());
        if ($params->export) {
            $fileName = vsprintf("%s_%s_%s", [
                ActivityModel::query()->where("id", $params->activityId)->first()->name,
                "数据统计",
                date("Y_m_d_H_i_s", time())
            ]);
            dispatch(
                (new Export(
                    $fileName, Export::TYPE_SHOP_ACTIVITY_LIST, [
                        'data'   => (array)$params,
                        'userId' => $request->user()->id,
                    ]
                ))
            )->onQueue(Export::QUEUE_NAME);
            return $this->success([]);
        }

        return $this->success(ActivityDataService::joinStatistics($params));
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function joinStatisticsShopList(Request $request): JsonResponse
    {
        $params = ActivityValidate::joinStatisticsShopListValidate($request->all());

        if ($params->export) {
            $fileName = vsprintf("%s_%s_%s", [
                ActivityModel::query()->where("id", $params->activityId)->first()->name,
                ActivityModel::BUSINESS_EXPORT_TYPE_TEXT[$params->businessExportType] ?? '未定义的类型',
                date("Y_m_d_H_i_s", time())
            ]);
            dispatch(
                (new Export(
                    $fileName, Export::TYPE_SHOP_ACTIVITY_SHOP_LIST, [
                        'data'   => (array)$params,
                        'userId' => $request->user()->id,
                    ]
                ))
            )->onQueue(Export::QUEUE_NAME);
            return $this->success([]);
        }

        return $this->success(ActivityDataService::joinStatisticsShopList($params));
    }
}
